"""
移除 chat_sessions.knowledge_base_id 的外键约束
因为该字段现在支持存储多个知识库ID（逗号分隔）
"""
import sys
import os

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from sqlalchemy import create_engine, text
from app.core.config import settings
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def remove_foreign_key():
    """移除外键约束"""
    engine = create_engine(settings.DATABASE_URL)
    
    with engine.connect() as conn:
        # 查找外键约束名称
        logger.info("查找 chat_sessions.knowledge_base_id 的外键约束...")
        result = conn.execute(text("""
            SELECT constraint_name 
            FROM information_schema.table_constraints 
            WHERE table_name = 'chat_sessions' 
            AND constraint_type = 'FOREIGN KEY'
            AND constraint_name LIKE '%knowledge_base%'
        """))
        
        constraint = result.fetchone()
        
        if constraint:
            constraint_name = constraint[0]
            logger.info(f"找到外键约束: {constraint_name}")
            
            # 删除外键约束
            logger.info(f"删除外键约束 {constraint_name}...")
            conn.execute(text(f"""
                ALTER TABLE chat_sessions 
                DROP CONSTRAINT IF EXISTS {constraint_name}
            """))
            
            conn.commit()
            logger.info("✅ 外键约束已删除")
        else:
            logger.info("未找到外键约束，可能已经删除过了")


def verify_fix():
    """验证修复结果"""
    engine = create_engine(settings.DATABASE_URL)
    
    with engine.connect() as conn:
        logger.info("\n检查 chat_sessions 表的约束:")
        result = conn.execute(text("""
            SELECT constraint_name, constraint_type 
            FROM information_schema.table_constraints 
            WHERE table_name = 'chat_sessions'
        """))
        
        for row in result:
            logger.info(f"  {row[0]}: {row[1]}")


if __name__ == "__main__":
    try:
        logger.info("开始移除外键约束...")
        remove_foreign_key()
        verify_fix()
        logger.info("\n🎉 修复完成！chat_sessions.knowledge_base_id 现在可以存储多个知识库ID")
        logger.info("请重启后端服务以应用更改")
    except Exception as e:
        logger.error(f"❌ 修复失败: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

